<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Logs;

/**
 * LogsSearch represents the model behind the search form about `common\models\Logs`.
 */
class LogsSearch extends Logs
{

    public $created_at_start;
    public $created_at_end;

    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
      return array_merge(
        parent::attributeLabels(),
        [
        'created_at_start' => '开始时间',
        'created_at_end' => '结束时间',
        ]
      );
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'updated_at', 'deleted'], 'integer'],
            [['log_url', 'log_info', 'log_ip'], 'safe'],
            [['created_at_start','created_at_end', 'created_at'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
    * @param array() $params
    * @param int $pageSize
    * @param int $f 0|1
    * @return ActiveDataProvider
    */
    public function search($params,$pageSize = 20,$f = 0)
    {
        $query = Logs::find($f);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => &$query,
            'pagination' => ['pageSize'=>$pageSize],
            'sort'=>[
                'defaultOrder'=>[
                    'id'=> SORT_DESC,
                ],
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            //'created_at' => $this->created_at,
           // 'updated_at' => $this->updated_at,
           // 'deleted' => $this->deleted,
        ]);

        $query->andFilterWhere(['like', 'log_url', $this->log_url])
            ->andFilterWhere(['like', 'log_info', $this->log_info])
            ->andFilterWhere(['like', 'log_ip', $this->log_ip]);

        if(!empty($this->created_at_start) && !empty($this->created_at_end)){
          $query->andFilterWhere(['between', $this->a.'.created_at', strtotime($this->created_at_start),strtotime($this->created_at_end)]);
        }
      if ($this->created_at) {
        $createdAt = strtotime($this->created_at);
        $createdAtEnd = $createdAt + 24*3600;
        $query->andFilterWhere(['between', $this->a.'.created_at', $createdAt,$createdAtEnd]);
      }

        return $dataProvider;
    }
}
